import os
import django
import csv
import datetime
import zipfile
import sys
from xml.dom import minidom
from django.db.models import Q

pro_dir = os.getcwd()
sys.path.append(pro_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mitagger.settings")

from home.models import Tag, Image
from home.models import Ontology
from home.models import Annotations
from home.models import Recommendations
from home.models import ImageTag
from home.models import TagType
from home.models import ImageAssignments

head_keys = ['imageFileName','tagID','tagName','tag_fullID','ontologyName','ontologyVirtualId']

def generateFileName(fileFormat):
    baseURL = 'downloads/'
    return baseURL + 'new_missed.%s' % fileFormat

def get_images():
    image_id_list = ImageAssignments.objects.filter(user_id__in=['Olivia', 'dinghuitong']).values_list('image_id', flat=True)
    return image_id_list

def get_tag_ids(image_id):
    tag_id_list = ImageTag.objects.filter(image_id=image_id, isSelected=True, author_id__in=['Olivia', 'dinghuitong']).values_list('tag_id', flat=True)
    return tag_id_list

def format_tags(tag_id_list, iamgename):
    tags = Tag.objects.filter(id__in=tag_id_list)
    res = []
    for tag in tags:
        tag_info = {
            'imageFileName': iamgename,
            'tagID': tag.id,
            'tagName': tag.name,
            'tag_fullID': tag.fullId,
            'ontologyName':tag.ontology.name,
            'ontologyVirtualId': tag.ontology.virtual_id,
        }
        res.append(tag_info)
    return res

def get_image_filename(imageid):
    img = Image.objects.get(id=imageid)
    return img.file_name

def write_to_csv(tag_list):
    filename = generateFileName('csv')
    csv_writer = csv.writer(open(filename, 'wb'), delimiter=',')
    for tag_info in tag_list:
        row = list()
        for key in head_keys:
            row.append(tag_info[key])
        csv_writer.writerow(row)
    del csv_writer

def main():
    image_id_list = get_images()
    all_tags = []
    for image_id in image_id_list:
        all_tags.extend(format_tags(get_tag_ids(image_id), get_image_filename(image_id)))


